const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}

function addTwo(num) {
	if (parseInt(num) < 10) {
		return "0" + num;
	} else {
		return num
	}
}
export class Util {
	static GetQueryString(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]);
		return null;
	}
	//取倒计时（天时分秒）
	static getTimeLeft(datetimeTo) {
		// 计算目标与现在时间差（毫秒）
		/*let time1 = new Date(datetimeTo).getTime();
		let time2 = new Date().getTime();*/
		let mss = datetimeTo;

		// 将时间差（毫秒）格式为：天时分秒
		let days = parseInt(mss / (60 * 60 * 24));
		let hours = parseInt((mss % (60 * 60 * 24)) / (60 * 60));
		let minutes = parseInt((mss % (60 * 60)) / (60));
		let seconds = parseInt((mss % 60));
		//return days + "天" + hours + "时" + minutes + "分" + seconds + "秒"
		return {
			days: addTwo(days),
			hours: addTwo(hours),
			minutes: addTwo(minutes),
			seconds: addTwo(seconds)
		}
	}
	//时间格式化
	static formatTime(date) {
		console.log(date, "date")
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		const day = date.getDate();
		const hour = date.getHours();
		const minute = date.getMinutes();
		const second = date.getSeconds();
		return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
	}
	static getDayOfWeek(date) {
		date = new Date(date).getDay();
		switch (date) {
			case 0:
				return '周日';
				break;
			case 1:
				return '周一';
				break;
			case 2:
				return '周二';
				break;
			case 3:
				return '周三';
				break;
			case 4:
				return '周四';
				break;
			case 5:
				return '周五';
				break;
			case 6:
				return '周六';
				break;
			default:
				return null;
				break;
		}
	}
	// 匹配手机号码
	static testPhoneNum(data) {
		var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
		return reg.test(data);
	}
	// 匹配身份证号码
	static testIDCard(data) {
		var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
		return reg.test(data);
	}
	// 匹配邮箱地址
	static testEmail(data) {
		var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
		return reg.test(data);
	}
	// 匹配纳税人识别号
	static testTaxpayerID(data) {
		var reg = /(^[a-zA-Z0-9]{15}$)|(^[a-zA-Z0-9]{18}$)/;
		return reg.test(data);
	}
	// 去掉富文本框导致的比较难看的文本
	static replaceFullText(data) {
		return data.replace(/<\/?[^>]*>/g, "").replace(/[&nbsp;]|[&ensp;]|[&emsp;]|[&thinsp;]|[&zwnj;]|[&zwj;]/g, "");
	}
	/**
	 * @constructor loading提示框
	 * @param {String} title 提示的内容
	 * @param {Boolean} state 显示还是隐藏
	 * @param {Boolean} mask 是否显示透明蒙层，防止触摸穿透
	 */
	static loading(state = false, title, mask = true) {
		return new Promise((resolve, reject) => {
			if (state) {
				let data = {
					title,
					mask,
					success: resolve,
					fail: reject
				};
				wx.showLoading(data);
			} else {
				let data = {
					success: resolve,
					fail: reject
				};
				wx.hideLoading(data);
			}
		});
	}
	/**
	 * @constructor 消息提示框
	 * @param {*} title 
	 * @param {*} param 
	 */
	static showToast(title, param = {
		icon: '',
		image: '',
		duration: 1500,
		mask: false
	}) {
		return new Promise((resolve, reject) => {
			let data = {
				title,
				duration: param.duration || 1500,
				mask: param.mask || false,
				success: resolve,
				fail: reject
			};
			if (param.icon && !param.icon.IsNullOrEmpty()) {
				data.icon = param.icon;
			} else {
				data.icon = 'none';
			}
			if (param.image && !param.image.IsNullOrEmpty()) {
				data.image = param.image;
			}
			wx.showToast(data);
		});
	}
	/**
	 * @constructor 模态框
	 * @param {*} title 
	 * @param {*} content 
	 * @param {*} showCancel 
	 * @param {*} cancelText 
	 * @param {*} cancelColor 
	 * @param {*} confirmText 
	 * @param {*} confirmColor 
	 */
	static showModal(title, content, showCancel = false, cancelText = "取消", cancelColor = "#000000", confirmText = "确定",
		confirmColor = "#3CC51F") {
		return new Promise((resolve, reject) => {
			wx.showModal({
				title,
				content,
				showCancel,
				cancelText,
				cancelColor,
				confirmText,
				confirmColor,
				success: (res) => {
					resolve(res.confirm);
				},
				fail: reject
			});
		});
	}
	static GetAuthState() {
		return new Promise((resolve, reject) => {
			wx.getSetting({
				success: (res) => {
					if (res.authSetting['scope.userInfo'] === undefined) {
						resolve(0);
					}
					if (res.authSetting['scope.userInfo'] === true) {
						resolve(1);
					}
					if (res.authSetting['scope.userInfo'] === false) {
						resolve(2);
					}
				},
				fail: reject
			});
		})
	}
	static ChooseImage(count = 9, sizeType = ['original', 'compressed'], sourceType = ['album', 'camera']) {
		return new Promise((resolve, reject) => {
			wx.chooseImage({
				count,
				sizeType,
				sourceType,
				success: resolve,
				fail: reject
			});
		})
	}
	static Sleep(times = 0) {
		return new Promise((resolve, reject) => {
			setTimeout(function() {
				resolve();
			}, times)
		})
	}
	static ToParams(obj) {
		return Object.keys(obj).map(function(key) {
			// body...
			return encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
		}).join("&");
	}
	static wxPromisify(fn) {
		return function(obj = {}) {
			return new Promise((resolve, reject) => {
				obj.success = function(res) {
					resolve(res)
				}

				obj.fail = function(res) {
					reject(res)
				}

				fn(obj)
			})
		}
	}
}
